const fs = require('fs')
const path = require('path')
const copyServe = require('./copyServe')
const alert = require('cli-alerts');

const PATH = {
  'bootstrap.yml': 'src/',
  'package.json': '',
  'README.md': ''
}

// 服务目录结构
module.exports = async function copyService (name) {
  const syncCopy = name => new Promise((resolve, reject) => {
    fs.cp(path.join(__dirname, '../../tpl/service'), `node-${name}`, { recursive: true }, err => {
      if (err) throw err;
      console.log('文件目录结构创建成功');
      copyServe(`node-${name}/src/modules/test`)
      console.log('创建test模块成功');
      let index = 0
      for (const file in PATH) {
        if (Object.hasOwnProperty.call(PATH, file)) {
          const p = PATH[file];
          fs.readFile(path.join(__dirname, '../../tpl/serviceChange', file), 'utf-8', (err, data) => {
            if (err) throw err;
            data = data.replace(/demo/g, name)
            fs.writeFile(`node-${name}/${p}${file}`, data, err => {
              if(err) throw err;
              index++
              console.log(`${file} 文件创建成功`);
              if (index === Object.keys(PATH).length) {
                resolve()
              }
            })
          })
        }
      }
    })
  })
await syncCopy(name)
alert({
      type: `success`,
      name: `创建成功`,
      msg: `
      
cd node-${name}
npm install || yarn
      `
  })
  
}
